package pers.qianyu.month_202012.date_20201222;

import org.junit.*;
import pers.qianyu.util.model.*;

import java.util.*;

/**
 * [leetcode 每日一题]
 * 103. 二叉树的锯齿形层序遍历
 * https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
 *
 * @author mizzle rain
 * @date 2020-12-22 14:10
 */
public class ZigzagLevelOrder {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        ArrayList<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        boolean reverse = false;
        while (!q.isEmpty()) {
            int size = q.size();
            // 双端队列
            LinkedList<Integer> list = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = q.poll();
                if (reverse) {
                    list.offerFirst(node.val);
                } else {
                    list.offerLast(node.val);
                }
                if (node.left != null) {
                    q.add(node.left);
                }
                if (node.right != null) {
                    q.add(node.right);
                }
            }
            res.add(list);
            reverse = !reverse;
        }
        return res;
    }

    // 测试双端队列
    @Test
    public void test1() {
        Deque<Integer> q = new LinkedList<>();
        q.offerFirst(1);
        q.offerFirst(2);
        q.offerFirst(3);
        System.out.println(q);
        q.offerLast(4);
        q.offerLast(5);
        q.offerLast(6);
        System.out.println(q);
    }
}
